package org.linlinjava.litemall.mechanismadmin.web;

import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.util.bcrypt.BCryptPasswordEncoder;
import org.linlinjava.litemall.db.domain.LitemallMechanism;
import org.linlinjava.litemall.db.domain.LitemallMechanismUser;
import org.linlinjava.litemall.db.service.LitemallMechanismService;
import org.linlinjava.litemall.db.service.LitemallMechanismUserService;
import org.linlinjava.litemall.mechanismadmin.annotation.LoginAdmin;
import org.linlinjava.litemall.mechanismadmin.service.AdminTokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/mechanismadmin/mechanismUser")
public class MechanismLitemallMechanismUserController {
    private final Log logger = LogFactory.getLog(MechanismLitemallMechanismUserController.class);
    @Autowired
    private LitemallMechanismUserService litemallMechanismUserService;

    private static final String SYMBOLS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    private static final Random RANDOM = new SecureRandom();

    @Autowired
    private LitemallMechanismService litemallMechanismService;
    @GetMapping("/info")
    public Object info(String token){
        Integer adminId = AdminTokenManager.getUserId(token);
        if(adminId == null){
            return ResponseUtil.badArgumentValue();
        }
        LitemallMechanismUser mechanismUser = litemallMechanismUserService.findById(adminId);
        if(mechanismUser == null){
            return ResponseUtil.badArgumentValue();
        }
        Integer mechanismId = mechanismUser.getMechanismId();
        LitemallMechanism mechanism = litemallMechanismService.findById(mechanismId);

        String num;
        if(!mechanism.getLevel().equals((byte)1)&& StringUtils.isBlank(mechanism.getReferCode())){
            boolean flag = false;
            do {
                num = generateNonceStr();
                LitemallMechanism litemallMechanism = litemallMechanismService.findByReferCode(num);
                if(litemallMechanism==null){
                    flag=true;
                }
            }while (!flag);
            mechanism.setReferCode(num);
            litemallMechanismService.updateById(mechanism);
        }else{
            num = mechanism.getReferCode();
        }
        Map<String, Object> data = new HashMap<>(6);
        data.put("name", mechanismUser.getUsername());
        data.put("fullName", mechanismUser.getFullName());
        data.put("mechanismId", mechanismUser.getMechanismId());
        data.put("mechanismName",mechanism.getName());
        data.put("avatar", mechanismUser.getAvatar());
        data.put("referCode",num);
        // 目前roles不支持，这里简单设置admin
        List<String> roles = new ArrayList<>();
        roles.add("admin");
        data.put("roles", roles);
        data.put("introduction", "admin introduction");
        return ResponseUtil.ok(data);
    }

    /**
     * 生成5位随机数
     * @return String 03D56
     */
    private synchronized String generateNonceStr(){
        char[] nonceChars = new char[5];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }

    @GetMapping("/list")
    public Object list(@LoginAdmin Integer adminId,
                       String username, String fullName,
                       Integer mechanismId,
                       @RequestParam(value = "page", defaultValue = "1") Integer page,
                       @RequestParam(value = "limit", defaultValue = "10") Integer limit,
                       String sort, String order){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }

        List<LitemallMechanismUser> adList = litemallMechanismUserService.querySelective(mechanismId,username, fullName, page, limit, sort, order);
        long total = PageInfo.of(adList).getTotal();
        Map<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("items", adList);

        return ResponseUtil.ok(data);
    }

    @PostMapping("/create")
    public Object create(@LoginAdmin Integer adminId, @RequestBody LitemallMechanismUser litemallMechanismUser){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }
        litemallMechanismUser.setAddTime(LocalDateTime.now());

        String rawPassword = litemallMechanismUser.getPassword();

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encodedPassword = encoder.encode(rawPassword);
        litemallMechanismUser.setPassword(encodedPassword);
        litemallMechanismUserService.add(litemallMechanismUser);
        return ResponseUtil.ok(litemallMechanismUser);
    }

    @GetMapping("/read")
    public Object read(@LoginAdmin Integer adminId, Integer id){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }

        if(id == null){
            return ResponseUtil.badArgument();
        }

        LitemallMechanismUser brand = litemallMechanismUserService.findById(id);
        return ResponseUtil.ok(brand);
    }

    @PostMapping("/update")
    public Object update(@LoginAdmin Integer adminId, @RequestBody LitemallMechanismUser ad){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }

        String rawPassword = ad.getPassword();
        if (rawPassword != null && !rawPassword.equals("")) {
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            String encodedPassword = encoder.encode(rawPassword);
            ad.setPassword(encodedPassword);
        }

        String username = ad.getUsername();
        username.replaceAll(" ", "");
        ad.setUsername(username);
        String fullName = ad.getFullName();
        fullName = fullName.replaceAll(" ", "");
        ad.setFullName(fullName);
        litemallMechanismUserService.update(ad);
        return ResponseUtil.ok(ad);
    }

    @PostMapping("/delete")
    public Object delete(@LoginAdmin Integer adminId, @RequestBody LitemallMechanismUser ad){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }
        litemallMechanismUserService.deleteById(ad.getId());
        return ResponseUtil.ok();
    }
}
